﻿using System;
using UnityEngine;

namespace HBFramework
{
    /// <summary>
    /// 计数计时器
    /// </summary>
    public class CountTimer : ITimer
    {
        private float interval;
        private int count;
        private Action onUpdate;
        private Action onRelease;

        private float startTime;
        private int curCount;
        private bool isStop;

        bool ITimer.IsStop => isStop;

        public CountTimer(float interval, int count, Action onUpdate, Action onRelease)
        {
            this.interval = interval;
            this.count = count;
            this.onUpdate = onUpdate;
            this.onRelease = onRelease;
        }

        void ITimer.OnStart()
        {
            startTime = Time.time;
            curCount = 0;
        }

        void ITimer.OnUpdate()
        {
            float spendTime = Time.time - startTime;
            if (spendTime <= interval)
            {
                return;
            }
            onUpdate?.Invoke();
            if (count != -1)
            {
                curCount++;
                if (curCount >= count)
                {
                    TimerManager.Instance.StopTimer(this);
                }
            }
        }

        void ITimer.OnStop()
        {
            onRelease?.Invoke();
        }
    }
}